package com.app.business.web.business;

import com.app.business.service.AzProjectService;
import com.app.business.service.HouseService;
import com.app.business.service.UserInfoForPropertyService;
import com.app.system.common.EncipherPwd;
import com.app.system.jpa.PageBean;
import com.app.system.permission.model.Department;
import com.app.system.permission.model.SysRole;
import com.app.system.permission.model.UserInfo;
import com.app.system.permission.service.DataDictService;
import com.app.system.permission.service.SysRoleService;
import com.app.system.permission.service.UserInfoService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.exception.AjaxException;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by ddz on 2020/5/8.
 * 物业管理
 */
@Controller
@RequestMapping("/business/userInfoForProperty/*")
@SuppressWarnings("all")
public class UserInfoForPropertyController {

    @Autowired
    private UserInfoForPropertyService userInfoForPropertyService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private DataDictService dataDictService;
    @Autowired
    private AzProjectService azProjectService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private HouseService houseService;
    @Autowired
    private EncipherPwd encipherPwd;

    /**
     * 办证物业用户管理列表
     */
    @RequestMapping("list")
    @RequiresPermissions("userInfoForProperty:list")
    public void list(ModelMap modelMap) {
        List<SysRole> sysRoleList = this.sysRoleService.findAll();
        modelMap.addAttribute("sysRoleList", sysRoleList);
    }

    private String getRoleNames(Set<SysRole> set) {
        StringBuffer sb = new StringBuffer("");
        if (CollectionUtils.isNotEmpty(set)) {
            for (SysRole sysRole : set) {
                if (sb.length() > 0) {
                    sb.append("、");
                }
                sb.append(sysRole.getRole());
            }
        }
        return sb.toString();
    }

    /**
     * 加载物业用户管理列表
     *
     * @return
     */
    @RequestMapping("loadUserInfoForPropertyList")
    @ResponseBody
    @RequiresPermissions("userInfoForProperty:loadUserInfoForPropertyList")
    public Map loadUserInfoForPropertyList() {
        List<Map> listData = Lists.newArrayList();
        PageBean<UserInfo> userInfoPageBean = this.userInfoService.getUserInfoForPropertyPageBeen();
        List<UserInfo> userInfoList = userInfoPageBean.getDatas();
        if (!CollectionUtils.isEmpty(userInfoList)) {
            Map<String, Object> item = null;
            for (UserInfo userInfo : userInfoList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", userInfo.getId());
                item.put("departmentName", userInfo.getDepartment() == null ? "" : userInfo.getDepartment().getName());
                item.put("username", userInfo.getUsername());
                item.put("name", userInfo.getName());
                item.put("roles", getRoleNames(userInfo.getRoleList()));
                item.put("state", Integer.valueOf(userInfo.getState()));
                listData.add(item);
            }
        }
        return LayUiUtils.page(userInfoPageBean.getTotalCount().intValue(), listData);
    }


    //物业管理增加页面
    @RequestMapping("form")
    @RequiresPermissions("userInfoForProperty:form")
    public void form(HttpServletRequest request, ModelMap model) {
        int id = ParamUtils.getInt(request, "id", 0);
        UserInfo userInfo = this.userInfoService.findOneById(id);
        if (userInfo == null) {
            userInfo = new UserInfo();
        }
        System.out.println(userInfo.getId());
        model.addAttribute("userInfo", userInfo);

        Set<SysRole> userRoleSet = userInfo.getRoleList();
        List<Integer> roleIds = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(userRoleSet)) {
            for (SysRole sysRole : userRoleSet) {
                roleIds.add(sysRole.getId());
            }
        }
        model.addAttribute("roleIds", roleIds);

        List<SysRole> sysRoleList = this.userInfoForPropertyService.getSysRoleListForProperty();
        model.addAttribute("sysRoleList", sysRoleList);
    }

    //增加物业管理用户保存
    @RequestMapping("save")
    @ResponseBody
    @RequiresPermissions("userInfoForProperty:save")
    public synchronized Response save(HttpServletRequest request) throws AjaxException {
        int id = ParamUtils.getInt(request, "id", 0);
        UserInfo userInfo = this.userInfoService.findOneById(id);
        if (userInfo == null) {
            userInfo = new UserInfo();
        }
        ServletRequestDataBinder binder = new ServletRequestDataBinder(userInfo);
        binder.bind(request);

        int[] roles = ParamUtils.getIntParameters(request, "role");
        Set<SysRole> sysRoleList = Sets.newHashSet();
        if (roles != null && roles.length > 0) {
            for (int r : roles) {
                SysRole sysRole = new SysRole();
                sysRole.setId(r);
                sysRoleList.add(sysRole);
            }
        }
        userInfo.setRoleList(sysRoleList);
        int departmentId = ParamUtils.getInt(request, "departmentId", 0);
        if (departmentId > 0) {
            Department department = new Department();
            department.setId(departmentId);
            userInfo.setDepartment(department);
        }
        this.userInfoService.saveBeforeValidateUserName(userInfo);

        return new Response("0001", "保存成功");
    }

    //删除用户
    @RequestMapping("delById")
    @ResponseBody
    @RequiresPermissions("userInfoForProperty:delById")
    public Response delById(HttpServletRequest request) {
        String ids = ParamUtils.getString(request, "ids", "");
        if (ids != null && ids.length() > 0) {
            String[] idsArray = ids.split(",");
            List<Integer> idsLists = Lists.newArrayList();
            for (String id : idsArray) {
                idsLists.add(Integer.valueOf(id));
            }
            this.userInfoService.delByIds(idsLists);
        }
        return new Response("0001", "删除成功");
    }

    //设置用户状态
    @RequestMapping("setState")
    @ResponseBody
    @RequiresPermissions("userInfoForProperty:setState")
    public Response setState(HttpServletRequest request) {
        Integer id = ParamUtils.getInt(request, "id", 0);
        Integer state = ParamUtils.getInt(request, "state", 0);
        UserInfo userInfo = this.userInfoService.findOneById(id);
        Precondition.checkAjaxArguement(userInfo != null, "1111", "无效操作");
        userInfo.setState(state);
        this.userInfoService.save(userInfo);
        return new Response("0001", "更新成功");
    }

    //修改密码页面
    @RequestMapping(value = "pwdForm")
    @RequiresPermissions("userInfoForProperty:pwdForm")
    public void pwdForm(HttpServletRequest request, int id, ModelMap model) {
        UserInfo userInfo = this.userInfoService.findOneById(id);
        Precondition.checkSqdsArguement(userInfo != null, "无效操作");
        model.addAttribute("userInfo", userInfo);
    }

    //修改密码保存
    @RequestMapping(value = "savePwd", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("userInfoForProperty:savePwd")
    public Response savePwd(HttpServletRequest request) {

        String username = ParamUtils.getString(request, "username", "");
        String pwd = ParamUtils.getString(request, "pwd", "");
        UserInfo userInfo = this.userInfoService.findByUsername(username);
        Precondition.checkAjaxArguement(userInfo != null, "1111", "无效操作");

        Map<String, String> map = encipherPwd.getEncipherPwd(username, pwd);
        String encipher_password = map.get("password");
        String encipher_salt = map.get("salt");

        this.userInfoService.updatePwd(userInfo.getId(), encipher_password, encipher_salt);

        return new Response("0001", "更新成功");
    }


    @RequestMapping(value = "setPwd", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("userInfoForProperty:setPwd")
    public Response setPwd(HttpServletRequest request) {

        String newPwd = ParamUtils.getString(request, "newPwd", "");
        String confirmPwd = ParamUtils.getString(request, "confirmPwd", "");

        Precondition.checkAjaxArguement(newPwd.equals(confirmPwd), "1111", "两次密码不一致");

        String username = ParamUtils.getString(request, "username", "");
        String oldPwd = ParamUtils.getString(request, "oldPwd", "");
        UserInfo userInfo = this.userInfoService.findByUsername(username);
        Precondition.checkAjaxArguement(userInfo != null, "1111", "无效操作");

        String credentialsPwd = encipherPwd.getCredentialsPwd(userInfo.getUsername(), oldPwd, userInfo.getSalt());
        Precondition.checkAjaxArguement(credentialsPwd.equals(userInfo.getPassword()), "1111", "原始密码输入有误");

        Map<String, String> map = encipherPwd.getEncipherPwd(username, newPwd);
        String encipher_password = map.get("password");
        String encipher_salt = map.get("salt");

        this.userInfoService.updatePwd(userInfo.getId(), encipher_password, encipher_salt);

        return new Response("0001", "更新成功");
    }

    //分配房屋权限
    @RequestMapping("setAzProjectNamePermission")
    @SuppressWarnings("userInfoForProperty:setAzProjectNamePermission")
    public void setAzProjectNamePermission(HttpServletRequest request, ModelMap modelMap) {
        Map<String, String> townMap = this.dataDictService.getMapByParentNameForValue_Name("乡镇");
        int userInfoId = ParamUtils.getInt(request, "userInfoId", 0);
        UserInfo userInfo = this.userInfoService.findOne(userInfoId);
        Precondition.checkSqdsArguement(userInfo != null, "用户信息不存在！");
        List<String> townList = this.azProjectService.getTownList();
        modelMap.addAttribute("userInfo", userInfo);
        modelMap.addAttribute("roles", getRoleNames(userInfo.getRoleList()));

        modelMap.addAttribute("townList", townList);
        modelMap.addAttribute("townMap", townMap);
    }


    /**
     * 得到菜单及已分配数据json
     *
     * @param request
     * @return
     */
    @RequestMapping("memuJson")
    @ResponseBody
    @RequiresPermissions("userInfoForProperty:memuJson")
    public Map memuJson(HttpServletRequest request) {
        String townName = ParamUtils.getString(request, "townName", "");
        List<Map> listData = this.userInfoForPropertyService.getPropertyForHouseNum(townName);
        int userInfoId = ParamUtils.getInt(request, "userInfoId", 0);
        List<String> buildList = this.userInfoForPropertyService.findByUserIdAndTowm(userInfoId);//得到某项目下已选菜单
        Map result = Maps.newHashMap();
        result.put("list", listData);
        result.put("checkedIds", buildList);
        return result;
    }

    /**
     * 保存权限菜单分配设置
     *
     * @param request
     * @return
     */
    @RequestMapping("saveAzProjectNamePermission")
    @ResponseBody
    @RequiresPermissions("userInfoForProperty:saveAzProjectNamePermission")
    public Response saveFunctionName(HttpServletRequest request) {
        return this.userInfoForPropertyService.saveAzProjectNamePermission(request);
    }
}
